﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.Security;
using System.Security;
using System.Web;
using Utility;

namespace WebModel
{
	/// <summary>
	/// 基本页面模型
	/// </summary>
	public class PageBase : Page
	{
		protected class UnauthorizedActionEventArgs : EventArgs
		{
			private string m_RuleName;
			public string RuleName
			{
				get { return m_RuleName; }
				set { m_RuleName = value; }
			}

			private string m_FailedMessage;
			public string FailedMessage
			{
				get { return m_FailedMessage; }
				set { m_FailedMessage = value; }
			}

			public UnauthorizedActionEventArgs(string ruleName, string failedMessage)
			{
				this.m_RuleName = ruleName;
				this.m_FailedMessage = failedMessage;
			}
		}
		protected delegate void UnauthorizedActionEventHandler(object sender, UnauthorizedActionEventArgs e);
		/// <summary>
		/// 在当前身份不符合授权规则时发生
		/// </summary>
		protected event UnauthorizedActionEventHandler UnauthorizedAction;

		protected DateTime PageStartTime;
		/// <summary>
		/// Action 调用方法目录
		/// </summary>
		protected Dictionary<string, Action> ActionDict = new Dictionary<string, Action>();
		protected string RequestAction { get { return Request.QueryString["action"]; } }

		/// <summary>
		/// 页面执行时间
		/// </summary>
		protected TimeSpan PageSpendTime
		{
			get { return DateTime.Now - PageStartTime; }
		}

		protected PageBase()
		{
			PageStartTime = DateTime.Now;
		}

		/// <summary>
		/// 当前登录身份用户
		/// </summary>
		protected internal MembershipUser CurrentUser
		{
			get
			{
				if (Page.User.Identity.IsAuthenticated)
				{
					return (MembershipUser)Session["CurrentUser"] ?? Membership.GetUser(Page.User.Identity.Name, false);
				}
				else
				{
					return null;
				}
			}
			set
			{
				Session["CurrentUser"] = value;
			}
		}

		/// <summary>
		/// 登录
		/// </summary>
		/// <param name="UserAccount">用户名</param>
		/// <param name="Password">密码</param>
		/// <param name="isPersistent">若要创建持久 Cookie（跨浏览器会话保存的 Cookie），则为 true；否则为 false。</param>
		/// <returns>是否成功登录</returns>
		protected internal bool UserLogin(string UserAccount, string Password, bool isPersistent)
		{
			bool result = Membership.Provider.ValidateUser(UserAccount, Password);
			if (result)
			{
				MembershipUser currentUser = Membership.Provider.GetUser(UserAccount, false);
				this.CurrentUser = currentUser;

				FormsAuthentication.SetAuthCookie(UserAccount, isPersistent);

				//FormsAuthenticationTicket ticket
				//    = new FormsAuthenticationTicket(1, UserAccout, DateTime.Now, DateTime.Now.AddMinutes(30), isPersistent, null, FormsAuthentication.FormsCookiePath);

				//string encTicket = FormsAuthentication.Encrypt(ticket);

				//Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

				//Response.Redirect(FormsAuthentication.GetRedirectUrl(UserAccout, isPersistent));
			}
			return result;
		}

		/// <summary>
		/// 退出登录
		/// </summary>
		protected internal void UserLogout()
		{
			this.CurrentUser = null;
			FormsAuthentication.SignOut();
		}

		/// <summary>
		/// 当前登录状态
		/// </summary>
		protected internal bool IsLogined
		{
			get
			{
				//return CurrentUser != null;
				return Page.User.Identity.IsAuthenticated;
			}
		}

		/// <summary>
		/// 验证登录状态，如果未登录则重定向到登录页面
		/// </summary>
		protected internal void CheckLogin()
		{
			CheckLogin(Page.Title, null);
		}
		/// <summary>
		/// 验证登录状态，如果未登录则重定向到登录页面
		/// </summary>
		/// <param name="ReturnPageTitle">需返回页面的标题</param>
		/// <param name="ReturnUrl">返回页面地址</param>
		protected internal void CheckLogin(string ReturnPageTitle, string ReturnUrl)
		{
			//if (!IsLogined)
			//{
			//    Response.Redirect("Login.aspx?ReturnPageTitle=" + Server.UrlEncode(ReturnPageTitle) + "&ReturnUrl=" + Server.UrlEncode(ReturnUrl));
			//}
			if (!Page.User.Identity.IsAuthenticated)
			{
				if (!string.IsNullOrEmpty(ReturnUrl))
				{
					Response.Redirect(FormsAuthentication.LoginUrl + "?ReturnPageTitle=" + Server.UrlEncode(ReturnPageTitle) + "&ReturnUrl=" + Server.UrlEncode(ReturnUrl));
				}
				else
				{
					FormsAuthentication.RedirectToLoginPage("ReturnPageTitle=" + Server.UrlEncode(ReturnPageTitle));
					Response.End();
				}
			}
		}

		/// <summary>
		/// 在页加载阶段结束时引发 System.Web.UI.Page.LoadComplete 事件。
		/// </summary>
		/// <param name="e">包含事件数据的 System.EventArgs。</param>
		protected override void OnLoadComplete(EventArgs e)
		{
			if (Request.HttpMethod == "GET")
			{
				OnHttpGET();
			}
			else if (Request.HttpMethod == "POST")
			{
				OnHttpPOST();
			}
			base.OnLoadComplete(e);
		}

		/// <summary>
		/// 当HttpMethod为“GET”时的处理操作
		/// </summary>
		protected virtual void OnHttpGET() { }
		/// <summary>
		/// 当HttpMethod为“POST”时的处理操作
		/// </summary>
		protected virtual void OnHttpPOST()
		{
			if (!string.IsNullOrEmpty(RequestAction))
			{
				if (ActionDict.ContainsKey(RequestAction))
				{
					Action action = ActionDict[RequestAction];
					object[] attributes = action.Method.GetCustomAttributes(false);
					foreach (object attribute in attributes)
					{
						if (attribute is AuthorizeRuleAttribute)
						{
							AuthorizeRuleAttribute attr = attribute as AuthorizeRuleAttribute;
							if (!SecurityHelper.Authorized(attr.RuleName))
							{
								if (UnauthorizedAction != null)
								{
									UnauthorizedAction.Invoke(action, new UnauthorizedActionEventArgs(attr.RuleName, attr.FailedMessage));
								}
								else
								{
									JsonResult.WriteError(attr.FailedMessage ?? "Unauthorized operation.");
								}
							}
						}
					}
					action.Invoke();
				}

				Response.End();
			}
		}
	}
}
